import { Layout } from "@/components/layout/layout";
import ProfileLayout from "@/components/layout/profileLayout";
import { showToast } from "@/components/toast";
import { useActions, useHttp } from "@/hooks";
import useMounted from "@/hooks/useMounted";
import { VisibilityOff, Visibility } from "@mui/icons-material";
import { Button, Input } from "@nextui-org/react";
import type { NextPage } from "next";
import Link from "next/link";
import { useRouter } from "next/router";
import { useState, KeyboardEvent, useRef, useEffect } from "react";

const PasswordResetPage: NextPage = () => {
  const [email, setEmail] = useState("");
  const [isVisibles, setIsVisibles] = useState({ one: false, two: false });
  const [passwords, setPasswords] = useState({ one: "", two: "" });

  const updatePasswords = (val: { one?: string; two?: string }) => {
    setPasswords((old) => ({ ...old, ...val }));
  };

  const updateIsVisibles = (val: { one?: boolean; two?: boolean }) => {
    setIsVisibles((old) => ({ ...old, ...val }));
  };

  const { isLoading, http } = useHttp();
  const router = useRouter();
  Object.assign(console, { useRouter });

  const getUserByResetKey = async () => {
    const passResetToken = router.query.resetKey;
    const res = await http.get(`/api/user`, { passResetToken });
    if (res?.success) {
      setEmail(res.data[0]?.email);
    }
  };

  const getUserByResetTokenRef = useRef(getUserByResetKey);
  getUserByResetTokenRef.current = getUserByResetKey;

  useEffect(() => {
    router.query.resetKey && getUserByResetTokenRef.current();
  }, [router.query.resetKey]);

  const { clearUserInfo } = useActions();

  const handleKeyUp = (e: KeyboardEvent) => {
    e.preventDefault();
    if (e.code === "Enter") {
      handleSubmit();
    }
  };

  const handleLogout = async () => {
    const res = await http.get("/api/logout", {}, { isWaitTips: true });
    if (res?.success) {
      clearUserInfo({});
      router.replace("/login");
    }
  };

  const handleSubmit = async () => {
    if (!email) {
      showToast("Please check your reset link");
      return;
    }

    const samePass = passwords.one === passwords.two;
    if (!samePass) {
      showToast("Passwords are not the same");
      return;
    }

    const passResetToken = router.query.resetKey;
    const password = passwords.one;
    const res = await http.post("/api/user/password/reset", {
      passResetToken,
      password,
    });

    if (res?.success) {
      setTimeout(handleLogout, 3000);
    }
    // console.log("🚀 ~ handleSubmit ~ res:", res);
  };

  return (
    <ProfileLayout>
      <div className="passwrod-reset-content  w-[500px] mx-auto">
        <h1 className="text-center my-6 font-[30px]">Password Reset</h1>
        <div className="reset-form">
          <div>
            <Input
              fullWidth
              color="default"
              isClearable={false}
              variant="bordered"
              radius="lg"
              size="md"
              type="email"
              isRequired
              label="Email"
              className="mb-4"
              disabled
              value={email}
              // onChange={(e) => setEmail(e.target.value)}
              // contentLeft={<Mail fill="currentColor" />}
            />

            <Input
              fullWidth
              color="default"
              variant="bordered"
              radius="lg"
              type={isVisibles.one ? "text" : "password"}
              isRequired
              size="md"
              label="New Password"
              value={passwords.one}
              onChange={(e) => updatePasswords({ one: e.target.value })}
              onKeyUp={handleKeyUp}
              endContent={
                <button
                  className="focus:outline-none"
                  type="button"
                  onClick={() => updateIsVisibles({ one: !isVisibles.one })}
                >
                  {isVisibles.one ? (
                    <VisibilityOff className="text-md text-default-400" />
                  ) : (
                    <Visibility className="text-md text-default-400" />
                  )}
                </button>
              }
            />

            <Input
              className="mt-4"
              fullWidth
              color="default"
              variant="bordered"
              radius="lg"
              type={isVisibles.two ? "text" : "password"}
              isRequired
              size="md"
              label="Repeated New Password"
              value={passwords.two}
              onChange={(e) => updatePasswords({ two: e.target.value })}
              onKeyUp={handleKeyUp}
              endContent={
                <button
                  className="focus:outline-none"
                  type="button"
                  onClick={() => updateIsVisibles({ two: !isVisibles.two })}
                >
                  {isVisibles.two ? (
                    <VisibilityOff className="text-md text-default-400" />
                  ) : (
                    <Visibility className="text-md text-default-400" />
                  )}
                </button>
              }
            />

            <div className="actions text-center mt-6">
              <Button
                color="primary"
                isLoading={isLoading}
                className="w-full"
                size="lg"
                onClick={handleSubmit}
              >
                Reset
              </Button>
            </div>
          </div>
        </div>
      </div>
    </ProfileLayout>
  );
};

export default PasswordResetPage;
